<?php
/**
 *  用户信息
*/

namespace app\api\service;

use app\api\model\Customer;
use app\api\model\RegionCountry;
use app\common\Calculate;
use app\facade\Basic;
use think\facade\Cache;
use think\facade\Config;
use app\api\model\Order;
use app\api\model\WholesalOrder;
use think\facade\Db;

class Users
{
    /**
     *  用户基本信息
    */
    public function information($param)
    {

        $where['id'] = $param['id'];
        $reslut['userInfo'] = Customer::where($where)->field('id as user_id,first_name,last_name,phone_code,phone,email,role')->find();
        $Carts = new Carts();
        $reslut['cartCount'] = $Carts->getCartCount($param);
        if($reslut['userInfo']){
            return Basic::data(0,'common.success',$reslut);
        } else {
            return Basic::data(1,'user.userInformationNotExist');
        }
    }


    /**
     *  用户基本信息
     */
    public function userinfo($param)
    {

        $where['id'] = $param['id'];
        $result = Customer::with([
            'avatar' => function ($query){
            },
        ])->where($where)->field('id as user_id,first_name,last_name,phone_code,phone,avatar_id,email,role')->find();

        unset($result->avatar_id);
        if ( !empty($result->avatar) ) {
            $result->avatar = $result->avatar->url;
            unset($result->avatar_id);
        } else {
            unset($result->avatar);
            $result->avatar = '';
        }

        return $result;
    }




    /**
     *  dashboard  用户仪表盘
     * */

    public function dashboard($param) {

        $data = [];
        $user = Customer::where(['id'=>$param['id'],'is_del'=>'0','login_status'=>1])
            ->field('id,last_login_time')
            ->find();

        if ( !$user ) {
            return Basic::data(1,'user.userInformationNotExist');
        }

        $data['last_login_time'] = $user->last_login_time ?? '--';

        // 查询普通订单
        $order_where = [];
        $order_where[] = ['user_id','=',$param['id']];
        $order_where[] = ['pay_status','in',[3,4]];
        $order_where[] = ['status','in',[30,40,50,100]];
        $order_where[] = ['is_del','=',0];
        $order = Db::table('db_order')->where($order_where)->field("COUNT(id) as count,SUM(pay_amount) as pay_amount")->find();

        if ( is_null($order['pay_amount'])) {
            $order['pay_amount'] = 0;
        }
        $data['total_count'] = $order['count'];
        $data['total_amount'] = $order['pay_amount'];

        $data['aov'] = 0;
        if ( $data['total_amount'] > 0  && $data['total_count'] > 0 ) {
            $data['aov'] = Calculate::pricecalc($data['total_amount'],'/',$data['total_count'],2);
        }

        $data['total_amount'] =  sprintf("%.2f", $data['total_amount']);
        $data['aov'] =  sprintf("%.2f", $data['aov']);

        return Basic::data(0,'common.success',$data);
    }


    /**
     *  用户信息
    */
    public function info($param)
    {

        $where['id'] = $param['id'];
        $customer = Customer::with([
            'avatar' => function ($query){
               $query->field('id,url');
            },
            'country' => function ($query) {
                $query->field('id,name');
            }
        ])->where($where)->field('id as user_id,phone,email,cusname,nickname,address,phone_code,role,avatar_id,country_id')->find();

        /* 判断头像是否存在 */
        if(isset($customer->avatar)){
            $customer->avatar_url = $customer->avatar->url;
            unset($customer->avatar);
        } else {
            $customer->avatar_url = '';
        }


        /* 判断国际是否存在 */
        if(!empty($customer->country)){

            $customer->country_id = $customer->country->id;
            $customer->country = $customer->country->name;
        } else {
            $customer->country_id = '';
            $customer->country = '';
        }



        if($customer){
            return Basic::data(0,'common.success',$customer);
        } else {
            return Basic::data(1,'user.userInformationNotExist');
        }
    }

    /**
     *  更新基础信息
     */
    public function setInfo( $param )
    {

        /* 查询国家名称 */
//        $country = RegionCountry::where('id',$param['country_id'])->find();
//
//        if( empty($country) ) {
//            return Basic::data(1,'user.countryIdNotExist');
//        }

        //$param['country'] = $country->name;
        $param['update_time'] = date("Y-m-d H:i:s",time());

        $customer = Customer::Update($param);
        if($customer){
            return Basic::data(0,'user.updateSuccessful');
        } else {
            return Basic::data(1,'user.updateFailed');
        }


    }

    /**
     *  更新手机号
     */
    public function updatePhone( $param )
    {

        $where['id'] = $param['id'];
        $customer = Customer::where($where)->find();

        if ( !$customer ) {
            return Basic::data(1,'user.userInformationNotExist');
        }

        /* 验证码验证 */
        if( !$param['code'] ){
            return Basic::data(1,'user.verificationCodeError');
        }

        $customer->phone = $param['phone'];
        $customer->phone_code = $param['phone_code'];
        $customer->update_time = date("Y-m-d H:i:s",time());

        if($customer->save()){
            return Basic::data(0,'user.updateSuccessful');
        } else {
            return Basic::data(1,'user.updateFailed');
        }

    }

    /**
     *  更新邮箱
     */
    public function updateEmail( $param )
    {

        $where['id'] = $param['id'];
        $customer = Customer::where($where)->find();

        if ( !$customer ) {
            return Basic::data(1,'user.userInformationNotExist');
        }

        /* 验证码验证 */
        if(!isset($param['code']) || !$param['code'] ){
            return Basic::data(1,'user.verificationCodeError');
        }
        if ( !$code = MailCheck::check($param) ){
            return Basic::data(1,'retrieve.verificationCodeError');
        }

        if ( $param['code'] != $code ){
            return Basic::data(1,'retrieve.verificationCodeError');
        }


        $customer->email = $param['email'];
        $customer->update_time = date("Y-m-d H:i:s",time());

        if($customer->save()){
            return Basic::data(0,'user.updateSuccessful');
        } else {
            return Basic::data(1,'user.updateFailed');
        }


    }


    /**
     *  更新密码
     */
    public function updatePassword( $param )
    {

        /* 不能和原密码一致 */
        if( $param['password'] == $param['new_password'] ) {
            return Basic::data(1,'user.cannotMatchOriginalPassword');
        }

        /* 密码重复 */
        if( $param['new_password'] !== $param['repeat_password'] ) {
            return Basic::data(1,'user.repeatPasswordAtypism');
        }

        $where['id'] = $param['id'];
        $customer = Customer::where($where)->find();

        if ( !$customer ) {
            return Basic::data(1,'user.userInformationNotExist');
        }

        /* 验证码密码 */
        $password_salt = Config::get('api.password_salt');
        $password = md5(md5($param['password'].$password_salt.$customer->create_time));

        if($customer->password !== $password) {
            return Basic::data(1,'user.verificationPasswordError');
        }

        /* 保存 */
        $new_password = md5(md5($param['new_password'].$password_salt.$customer->create_time));
        $customer->password = $new_password;
        $customer->update_time = date("Y-m-d H:i:s",time());

        if($customer->save()){

            /* 删除缓存 */
            Cache::delete($param['token']);
            return Basic::data(0,'user.updateSuccessful');
        } else {
            return Basic::data(1,'user.updateFailed');
        }

    }

    /**
     *  获取用户数据
    */
   public function getUserInfo($param){
       $where['id'] = $param['user_id'];
       return Customer::where($where)->field('id,phone,email,cusname,nickname,address,phone_code')->find();
   }

}
